/*************************************************************************
	> File Name: tcp_server.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/02 18:31
 ************************************************************************/

#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <ctype.h>
#include <memory>
#include <signal.h>
#include <cassert>
#include <unistd.h>
#include <cerrno>
#include <unordered_map>
#include "Tools/log.hpp"
#include "Tools/threadPool.hpp"
#include <sys/wait.h>
#include "Tools/task.hpp"

const int SIZE = 1024;

static void service(const int sock, const std::string &cli_ip, const uint16_t &cli_port, const std::string &thread_name)
{
    char buffer[SIZE];
    while (1) {
        memset(buffer, 0, sizeof buffer);
        if (read(sock, buffer, sizeof buffer - 1) > 0) {
            std::cout << thread_name << "|" << cli_ip << ":" << cli_port << "# " << buffer << std::endl;
        } else {
            logMessage(WARNING, "link shutdown.");
            break;
        }
        write(sock, buffer, strlen(buffer));
    }
    close(sock);
}

class TcpServer
{
public:
    TcpServer (const uint16_t port, std::string ip = "0.0.0.0"):_port(port), _ip(ip), _listensock(-1), _tp_ptr(ThreadPool<Task>::getThreadPool())
    {}

    void initServer()
    {
        if ((_listensock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            logMessage(FATAL, "create socket error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create socket success, listensock:%d", _listensock);
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        if ((bind(_listensock, (struct sockaddr*)&local, sizeof local)) < 0) {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
        if (listen(_listensock, gbacklog) < 0) {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "init server success");
    }

    void start()
    {
        _tp_ptr->run();
        while (1) {
            struct sockaddr_in src;
            socklen_t len = sizeof src;
            int servicesock = accept(_listensock, (struct sockaddr*)&src, &len);
            if (servicesock < 0) {
                logMessage(ERROR, "acccet error, %d:%s", errno, strerror(errno));
                continue;
            }
            uint16_t cli_port = src.sin_port;
            std::string cli_ip = inet_ntoa(src.sin_addr);
            logMessage(NORMAL, "link success, servicesock:%d|%s:%d\n", servicesock, cli_ip.c_str(), cli_port);
            Task t(servicesock, cli_ip, cli_port, service);
            _tp_ptr->pushTask(t);
        }
    }

private:
    const static int gbacklog = 20;
    uint16_t _port;
    std::string _ip;
    int _listensock;
    ThreadPool<Task> *_tp_ptr;
};
